package com.ruoyix.im.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.ruoyix.common.annotation.Log;
import com.ruoyix.common.annotation.RepeatSubmit;
import com.ruoyix.common.core.controller.BaseController;
import com.ruoyix.common.core.domain.PageQuery;
import com.ruoyix.common.core.domain.R;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.core.validate.AddGroup;
import com.ruoyix.common.core.validate.EditGroup;
import com.ruoyix.common.enums.BusinessType;
import com.ruoyix.common.helper.LoginHelper;
import com.ruoyix.common.utils.poi.ExcelUtil;

import com.ruoyix.im.domain.ImChatGroup;
import com.ruoyix.im.domain.ImChatGroupUser;
import com.ruoyix.im.domain.bo.ImChatGroupBo;
import com.ruoyix.im.domain.bo.ImChatGroupUserBo;
import com.ruoyix.im.domain.vo.BaseRequestVO;
import com.ruoyix.im.domain.vo.ImChatGroupVo;
import com.ruoyix.im.service.IImChatGroupService;
import com.ruoyix.im.service.IImChatGroupUserService;
import com.ruoyix.im.websocket.ImConfigConst;
import com.ruoyix.im.websocket.TioWebsocketStarter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tio.core.Tio;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 聊天群
 *
 * @author ruoyi
 * @date 2024-05-27
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/weblog/chatGroup")
public class ImChatGroupController extends BaseController {

    private final IImChatGroupService iImChatGroupService;
    private final IImChatGroupService imChatGroupService;
    private final IImChatGroupUserService imChatGroupUserService;


    /**
     * 查询聊天群列表
     */
    @SaCheckPermission("weblog:chatGroup:list")
    @GetMapping("/list")
    public TableDataInfo<ImChatGroupVo> list(ImChatGroupBo bo, PageQuery pageQuery) {
        return iImChatGroupService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出聊天群列表
     */
    @SaCheckPermission("weblog:chatGroup:export")
    @Log(title = "聊天群", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ImChatGroupBo bo, HttpServletResponse response) {
        List<ImChatGroupVo> list = iImChatGroupService.queryList(bo);
        ExcelUtil.exportExcel(list, "聊天群", ImChatGroupVo.class, response);
    }

    /**
     * 获取聊天群详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("weblog:chatGroup:query")
    @GetMapping("/{id}")
    public R<ImChatGroupVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iImChatGroupService.queryById(id));
    }

    /**
     * 新增聊天群
     */
    @SaCheckPermission("weblog:chatGroup:add")
    @Log(title = "聊天群", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ImChatGroupBo bo) {
        return toAjax(iImChatGroupService.insertByBo(bo));
    }

    /**
     * 修改聊天群
     */
    @SaCheckPermission("weblog:chatGroup:edit")
    @Log(title = "聊天群", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ImChatGroupBo bo) {
        return toAjax(iImChatGroupService.updateByBo(bo));
    }

    /**
     * 删除聊天群
     *
     * @param ids 主键串
     */
    @SaCheckPermission("weblog:chatGroup:remove")
    @Log(title = "聊天群", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iImChatGroupService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 创建群组
     */
    @PostMapping("/creatGroupCommon")
    public R<Void> creatGroup(@RequestBody ImChatGroup imChatGroup) {
        if (!StringUtils.hasText(imChatGroup.getGroupName())) {
            return R.fail(400, "参数异常！");
        }
        imChatGroupService.createGroupCommon(imChatGroup);
        return R.ok();
    }



    /**
     * 创建话题
     */
    @PostMapping("/creatGroupTopic")
    public R<Void> creatGroupTopic(@RequestBody ImChatGroup imChatGroup) {
        if (!StringUtils.hasText(imChatGroup.getGroupName())) {
            return R.fail(400, "参数异常！");
        }
        imChatGroupService.creatGroupTopic(imChatGroup);

        return R.ok();
    }




    /**
     * 更新组
     * <p>
     * 只有群主才能修改组
     */
    @PostMapping("/updateGroup")
    public R<Void> updateGroup(@RequestBody ImChatGroup imChatGroup) {

        iImChatGroupService.updateGroup(imChatGroup);
        return R.ok();
    }



    /**
     * 解散群
     */
    @GetMapping("/deleteGroup")
    public R<Void> deleteGroup(@RequestParam("id") Long id) {
        imChatGroupService.deleteGroup(id);
        return R.ok();
    }



    /**
     * 管理员查询所有群
     */
    @PostMapping("/listGroupForAdmin")
    public R<BaseRequestVO> listGroupForAdmin(@RequestBody BaseRequestVO baseRequestVO) {
        LambdaQueryChainWrapper<ImChatGroup> lambdaQuery = imChatGroupService.lambdaQuery();
        lambdaQuery.orderByDesc(ImChatGroup::getCreateTime).page(baseRequestVO);
        return R.ok(baseRequestVO);
    }

    /**
     * 加入话题
     */
    @GetMapping("/addGroupTopic")
    public R<Void> addGroupTopic(@RequestParam("id") Long id) {
        imChatGroupService.addGroupTopic(id);
        return R.ok();
    }



    /**
     * 用户查询所有群
     * <p>
     * 只查询审核通过和禁言的群
     */
    @GetMapping("/listGroup")
    public R<List<ImChatGroupVo>> listGroup() {
        List<ImChatGroupVo> groupVOS = imChatGroupService.listGroups();
        return R.ok(groupVOS);
    }


}
